package com.isunland.managesystem.base;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;

/**
 * 单选
 * 回传的是单选按钮的位置,从0开始
 *
 * @author wangyanan
 */
public class BaseSingleChoiceDialogFragment extends DialogFragment {
  private static final String EXTRA_CHOICE = "com.isunland.managesystem.ui.EXTRA_CHO";

  public static final String EXTRA_RESULT = "com.isunland.managesystem.ui.EXTRA_RESULT";
  private int[] mChoices;
  private String[] mChoicesString;

  /**
   * 初始化方法
   *
   * @param choices 每个选项的id组成的数组.
   */
  public static BaseSingleChoiceDialogFragment newInstance(int[] choices) {
    Bundle argsBundle = new Bundle();
    argsBundle.putIntArray(EXTRA_CHOICE, choices);

    BaseSingleChoiceDialogFragment fragment = new BaseSingleChoiceDialogFragment();
    fragment.setArguments(argsBundle);
    return fragment;
  }

  @Override public void onCreate(Bundle savedInstanceState) {
    mChoices = getArguments().getIntArray(EXTRA_CHOICE);
    if (mChoices.length > 0) {
      mChoicesString = new String[mChoices.length];
      for (int i = 0; i < mChoices.length; i++) {
        mChoicesString[i] = getActivity().getResources().getString(mChoices[i]);
      }
    }
    super.onCreate(savedInstanceState);
  }

  ;

  @Override public Dialog onCreateDialog(Bundle savedInstanceState) {
    return new AlertDialog.Builder(getActivity()).setItems(mChoicesString, new OnClickListener() {

      @Override public void onClick(DialogInterface dialog, int which) {
        setResult(which);
      }
    }).create();
  }

  private void setResult(int result) {
    if (getTargetFragment() == null) return;
    Intent i = new Intent();
    i.putExtra(EXTRA_RESULT, result);
    getTargetFragment().onActivityResult(getTargetRequestCode(), Activity.RESULT_OK, i);
  }
}
